package com.dxy.netty.tcppackagesolve;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @Description "LengthFieldBasedFrameDecoder和LengthFieldPrepender"长度字段方式解决拆包粘包-服务端处理器
 * @Author dangxianyue
 * @Date 2023/1/9 15:13
 */
public class LengthFieldNettyServerHandler extends ChannelInboundHandlerAdapter {

    private int count = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("channelActive打印" + Thread.currentThread().getName() + ctx.channel().remoteAddress());
        //如果此handler后续还有handler的话,只有调用了fireXXX才能向下继续调用
        ctx.fireChannelActive();
    }

    /**
     * 读取客户端发送的数据
     *
     * @param ctx 上下文对象, 含有通道channel，管道pipeline
     * @param msg 就是客户端发送的数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //使用了Stingdecoder所以这里接受到消息就是string类型的,不需要再次抓交换
        String responseMsg = "收到客户端的第" + (++count) + "个数据包";
        System.out.println(responseMsg + "：" + msg);
        ctx.writeAndFlush(Unpooled.copiedBuffer (responseMsg, CharsetUtil.UTF_8));
    }

    @Override
    //处理异常, 一般是需要关闭通道
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }
}

